package httpMiddleware

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go_gateway/dao"
	"go_gateway/middleware"
	"regexp"
	"strings"
)

// HTTPUrlRewriteMiddleware
// @Description: 根据一定规则重写Url
// @return gin.HandlerFunc
//
func HTTPUrlRewriteMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1.获取服务信息
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serviceInterface.(*dao.ServiceDetail)

		// 2.获取重写规则,每条规则以","分割
		urlRewriteRule := strings.Split(serviceDetail.HTTPRule.UrlRewrite, ",")
		for _, rule := range urlRewriteRule {
			detailRule := strings.Split(rule, " ")
			if len(detailRule) != 2 {
				continue
			}
			regexpStr, err := regexp.Compile(detailRule[0])
			if err != nil {
				continue
			}
			fmt.Println("before rewrite: ", c.Request.URL.Path)
			replacePath := regexpStr.ReplaceAll([]byte(c.Request.URL.Path), []byte(detailRule[1]))
			c.Request.URL.Path = string(replacePath)
			fmt.Println("after rewrite: ", c.Request.URL.Path)
		}
		c.Next()
	}
}
